package com.ccb.jyzx.expand.tiantouonline.controller;

import com.alibaba.fastjson.JSON;
import com.ccb.jyzx.expand.tiantouonline.bean.BatchInfo;
import com.ccb.jyzx.expand.tiantouonline.bean.FileInfo;
import com.ccb.jyzx.expand.tiantouonline.bean.FileTagsInfo;
import com.ccb.jyzx.expand.tiantouonline.contant.StatusContant;
import com.ccb.jyzx.expand.tiantouonline.service.BatchInfoService;
import com.ccb.jyzx.expand.tiantouonline.service.FileInfoService;
import com.ccb.jyzx.expand.tiantouonline.service.FileOpService;
import com.ccb.jyzx.expand.tiantouonline.service.FileTagsInfoService;
import com.ccb.jyzx.expand.tiantouonline.utils.ClassPathUtils;
import com.ccb.jyzx.expand.tiantouonline.utils.CommonIdUtils;
import com.ccb.jyzx.expand.tiantouonline.utils.FileExtenUtils;
import com.ccb.jyzx.expand.tiantouonline.utils.ParseDateUtils;
import com.ccb.jyzx.expand.tiantouonline.view.request.CommitFileListRequest;
import com.ccb.jyzx.expand.tiantouonline.view.request.FsGetFileIdRequest;
import com.ccb.jyzx.expand.tiantouonline.view.request.FsUploadFileInfoRequest;
import com.ccb.jyzx.expand.tiantouonline.view.request.FsUploadFileRespons;
import com.ccb.jyzx.expand.tiantouonline.view.response.SimpleResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author XIEFEI
 * @date 2019-11-18 15:55
 * @Description 文件处理
 **/
@Controller
@RequestMapping("/tto/file")
@Api(tags = "文件操作相关接口")
public class FileController {

    @Value("${file_cache_dir}")
    private String file_cache_dir;

    @Value("${nas_home_path}")
    private String nas_home_path;

    @Autowired
    FileOpService fileOpService;

    @Autowired
    FileInfoService fileInfoService;

    @Autowired
    BatchInfoService batchInfoService;

    @Autowired
    FileTagsInfoService fileTagsInfoService;

   @ResponseBody
   @PostMapping(value = "getFileId",consumes = "application/json;charset=UTF-8")
   @ApiOperation(value = "获取文件上传ID", notes = "获取文件上传ID")
   public SimpleResponseResult<String> getFileId(@RequestBody FsGetFileIdRequest json){
       //生成文件fileId和信息
       FileInfo fileInfo = new FileInfo();
       fileInfo.setId(CommonIdUtils.createFileId());
       fileInfo.setFileName(json.getFileName());
       fileInfo.setFileExten(FileExtenUtils.getFileExten(json.getFileName()));
       fileInfo.setCreateTime(ParseDateUtils.getFormateTimeLong());
       fileInfo.setUploadId(json.getUploadId());
       fileInfo.setUploadName(json.getUploadName());
       fileInfo.setTotalSize(json.getFileSize());
       fileInfo.setOpCode(json.getOpCode());
       fileInfo.setSavePath("/"+fileInfo.getCreateTime()/10000+ "/"+fileInfo.getId());

       //保存到数据库
       fileInfoService.save(fileInfo);

       return new SimpleResponseResult<String>(true,0,fileInfo.getId(),"请求成功");
   }

    @ResponseBody
    @PostMapping(value = "upload",consumes = "application/json;charset=UTF-8")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    public FsUploadFileRespons upload(@RequestBody FsUploadFileInfoRequest fileInfo, HttpServletResponse response){
        FsUploadFileRespons respons = new FsUploadFileRespons();

        if (fileInfo != null) {
            response.setStatus(500);
            if (StringUtils.isBlank(fileInfo.getFileId())) {
                respons.setMessage("请求参数错误:缺少fileId字段");
                respons.setCode(StatusContant.ERROR_CODE);
                return respons;
            }
            if (StringUtils.isBlank(fileInfo.getUpfile())) {
                respons.setMessage("请求参数错误:缺少upfile字段");
                respons.setCode(StatusContant.ERROR_CODE);
                return respons;
            }

            if (StringUtils.isBlank(fileInfo.getBlockId())) {
                respons.setMessage("请求参数错误:缺少blockId字段");
                respons.setCode(StatusContant.ERROR_CODE);
                return respons;
            }
            if(!StringUtils.isNumericSpace(fileInfo.getBlockId())){
                respons.setMessage("请求参数错误:blockId字段不合法");
                respons.setCode(StatusContant.ERROR_CODE);
                return respons;
            }
            if (StringUtils.isBlank(fileInfo.getBlockSize()) && !StringUtils.isNumeric(fileInfo.getBlockSize())) {
                respons.setMessage("请求参数错误:缺少blockSize字段或不合法");
                respons.setCode(StatusContant.ERROR_CODE);
                return respons;
            }
            return fileOpService.saveFile(fileInfo, response);
        } else {
            response.setStatus(500);
            respons.setMessage("错误:后台无法解析请求参数");
            respons.setCode(StatusContant.ERROR_CODE);
            return respons;

        }
    }

    @ResponseBody
    @PostMapping(value = "commitFileList",consumes = "application/json;charset=UTF-8")
    @ApiOperation(value = "保存提交报告", notes = "保存提交报告")
    public SimpleResponseResult<String> commitFileList(@RequestBody CommitFileListRequest[] json){

        String batchId = CommonIdUtils.createBatchId();
       if (json.length>0){

           Arrays.stream(json).forEach(cf->{

               //1,保存批次信息
               BatchInfo batchInfo= new BatchInfo();
               batchInfo.setId(CommonIdUtils.createUUID());
               batchInfo.setBatchId(batchId);
               batchInfo.setFileId(cf.getFileId());
               batchInfo.setCreateTime(ParseDateUtils.getFormateTimeLong());
               batchInfo.setUserId(cf.getUser_id());
               batchInfo.setUserName(cf.getUser_name());
               batchInfoService.save(batchInfo);

               //2,保存标签信息
               FileTagsInfo  tagsInfo= new FileTagsInfo();
               tagsInfo.setId( CommonIdUtils.createTagId());
               tagsInfo.setFileId(cf.getFileId());
               tagsInfo.setName(cf.getName());
               tagsInfo.setUserId(cf.getUser_id());
               tagsInfo.setUserName(cf.getUser_name());
               tagsInfo.setBatchId(batchId);
               tagsInfo.setMonth(cf.getMonth());
               tagsInfo.setYear(cf.getYear());
               tagsInfo.setQuarter(cf.getQuarter());

               tagsInfo.setWeek(cf.getWeek());
               if (cf.getType()!=null){
                   tagsInfo.setTypeId(cf.getType().getId());
                   tagsInfo.setTypeName(cf.getType().getName());
               }
               if (cf.getOne()!=null){
                   tagsInfo.setOneId(cf.getOne().getId());
                   tagsInfo.setOneName(cf.getOne().getName());
               }
               if (cf.getTwo()!=null){
                   tagsInfo.setTwoId(cf.getTwo().getId());
                   tagsInfo.setTwoName(cf.getTwo().getName());
               }
               if (cf.getThree()!=null){
                   tagsInfo.setThreeId(cf.getThree().getId());
                   tagsInfo.setThreeName(cf.getThree().getName());
               }
               if (cf.getTags()!=null){
                   tagsInfo.setTagId(cf.getTags().getId());
                   tagsInfo.setTagName(cf.getTags().getName());
               }
               tagsInfo.setCreateTime(ParseDateUtils.getFormateTimeLong());
               fileTagsInfoService.save(tagsInfo);

               //3,更新文件上传状态为已完成,这样定时任务好去合并
               fileInfoService.updateUpTag(cf.getFileId(),1);
           });
       }
        return new SimpleResponseResult<String>(true,0,batchId,"请求成功");

    }


    @GetMapping (value = "download")
    @ApiOperation(value = "文件下载")
    public void download(String fileId,HttpServletResponse response){
        if(StringUtils.isBlank(fileId)){
            PdfFileNoFound(response);
        }else{
            FileInfo byId = fileInfoService.getById(fileId);
            if (byId==null){
                PdfFileNoFound(response);
            }else{
                //TODO查询PDF文件并下载
                //先查缓存目录
                File pdf = new File(file_cache_dir,byId.getSavePath()+byId.getFileExten());
                System.out.println(pdf.getPath());
                if (!pdf.exists()){//如果缓存目录没有,就去nas查找
                    pdf = new File(file_cache_dir,byId.getSavePath()+byId.getFileExten());
                    if (!pdf.exists()){//如果nas下也没有,显示没找到
                        PdfFileNoFound(response);
                    }else{
                        downloadFile(response,pdf);
                    }
                }
                downloadFile(response,pdf);
            }
        }

    }


    //对pdfjs进行支持http://localhost:11111/pdfjs/web/viewer.html?file=http%3a%2f%2flocalhost%3a18180%2ftto%2ffile%2fpdfView%3ffileId%3dTTO20191121192420795764360801381
    @GetMapping (value = "pdfView")
    @ApiOperation(value = "pdf文件预览")
    public void getFileId(String fileId,HttpServletResponse response){
      if(StringUtils.isBlank(fileId)){
          PdfFileNoFound(response);
      }else{
          FileInfo byId = fileInfoService.getById(fileId);
          if (byId==null){
              PdfFileNoFound(response);
          }else{
              //TODO查询PDF文件并下载
              //先查缓存目录
              File pdf = new File(file_cache_dir,byId.getSavePath()+".pdf");
//              System.out.println(pdf.getPath());
              if (!pdf.exists()){//如果缓存目录没有,就去nas查找
                   pdf = new File(file_cache_dir,byId.getSavePath()+".pdf");
                   if (!pdf.exists()){//如果nas下也没有,显示没找到
                       PdfFileNoFound(response);
                   }else{
                       downloadFile(response,pdf);
                   }
              }
              downloadFile(response,pdf);
          }
      }

    }

    /**
     * PDF 文件未找到
     * @param response
     */
    private void PdfFileNoFound(HttpServletResponse response) {
        String classPath = ClassPathUtils.getClassPath();
        File fileLost = new File(classPath, "404.pdf");
        downloadFile(response,fileLost);
    }

    /**
     *
     * @param response
     * @param sourcefile
     */
    private void downloadFile(HttpServletResponse response, File sourcefile) {
        response.setCharacterEncoding("UTF-8");

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Length",sourcefile.length()+"" );
        // 设置文件名
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + sourcefile.getName());
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {

            ServletOutputStream os = response.getOutputStream();

            fis = new FileInputStream(sourcefile);
            bis = new BufferedInputStream(fis);

            int buff_limit = 8192;
            byte[] buffer = new byte[buff_limit];
            int i;
            while ((i = bis.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }
            os.flush();
            bis.close();
        } catch (IOException e) {
            response.setStatus(500);
            e.printStackTrace();

        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
